package com.suxin.spring.configuration;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @classname EnableConfigurationPropertiesRegistrar
 * @description [  ]
 * @date 2023/3/18 14:20
 */
public class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 注册 bean processor
        registerInfrastructureBeans(beanDefinitionRegistry);
        // 注册配置类
        final ConfigurationPropertiesRegistry registry = new ConfigurationPropertiesRegistry(beanDefinitionRegistry);
        getTypes(metadata).forEach(registry::registry);
    }

    private void registerInfrastructureBeans(BeanDefinitionRegistry registry) {
        ConfigurationPropertiesBindingPostProcessor.register(registry);
    }

    public List<Class<?>> getTypes(AnnotationMetadata metadata) {
        return metadata.getAnnotations().stream(EnableConfigurationProperties.class)
                .flatMap(mergedAnnotation -> Arrays.stream(mergedAnnotation.getClassArray("value")))
                .collect(Collectors.toList());
    }

}
